package com.uade.empresasdistribuidas.connection;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil
{
    private static final SessionFactory sessionFactory;
    private static ThreadLocal<Session> tl = new ThreadLocal<Session>();
    static
    {
        try
        {
        	 
             sessionFactory = new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex)
        {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }
    
    public static Session getSession(){
    	if (tl.get()==null){
    		tl.set(sessionFactory.openSession());
    	}
    	return tl.get();
    }

	public static void finalizeSession() {
		if (tl.get()!=null){
			tl.get().close();
			sessionFactory.close();
		}
		
	}
}
